var express = require('express');
var router = express.Router();
const timeStamp = require('time-stamp')
const MyQuery = require('../utils/db')

//引入配置文件
const { API_URL, verifyToken } = require('../utils/config')

//文件上传
const formidable = require('formidable');
const path = require('path')
const fs = require('fs')
const { v4: uuidv4 } = require('uuid');



router.get('/demo5', function (req, res, next) {
    res.send('个人中心模块')
});


//这两个需要token。但是我们还未讲。
//根据视频id获取某一个视频
router.get('/video',async (req,res,next)=>{
    
    let { id='' } = req.query
  
    let data = {}//最终要返回的数据格式  msg,status,result
    if( id == '' ){
        data = {
            msg:'请输入id',
            status:500
        }
        res.send(data)
        return
    }
    //1. 写sql
    let sql = `SELECT *,CONCAT('${API_URL}/uploads/videos/',video_src) AS video_src FROM e_video WHERE id = ${id} `
    //2. 执行sql
    let {result} = await MyQuery(sql) //{ err,result }

    //3. 要处理成规范、格式化的json数据
    data = {
        msg:'OK',
        status:200,
        result:result[0]
    }
    res.send( data )
})

//报名相当于是 往表里面添加数据
/*
    报名的思路其实和注册思路一样的。

    一个人只能报一个课程，报了终身受用。到底是否只能报一个都是由产品经理决定 。
    e_order表是存储订单的信息
        cid/mid: 表示当前mid的这个人报名了cid这门课程
    如果存储了就提示报过了，未存储则可以报名(insert添加)
*/
router.post('/study',async (req,res,next)=>{
    
    let { mid='',cid='' } = req.body
  
    let data = {}//最终要返回的数据格式  msg,status,result

    if( mid == '' || cid=='' ){
        data = {
            "msg": "请传递必要参数",
            "status": 500
        }
        res.send(data)
        return
    }

    //1. 写sql
    let sql = `SELECT * FROM e_order WHERE mid='${mid}' AND cid='${cid}' `
    //2. 执行sql有无此报名信息的sql
    let {result} = await MyQuery(sql) //{ err,result }
    if( result.length >0 ){
        data = {
            "msg": "已经报名此课程",
            "status": 500
        }
        res.send(data)
        return
    }

    let createdate = Date.now()
    let oid =  timeStamp('YYYYMMDDHHmmss') + (Math.random()+'').substring(2,8)//订单号，是唯一的。年月日时分秒+6位随机数
    let sql2 = ` INSERT INTO e_order ( oid,cid,mid,createdate )  VALUES ( '${oid}','${cid}','${mid}',${createdate} )`
    // res.send( result )
    // return
    let {result:result2} = await MyQuery(sql2) //{ err,result }

    // res.send( sql2 )
    // return
    //result2.affectedRows>0
    //3. 要处理成规范、格式化的json数据
    data = {
        msg:'OK',
        status:200
    }
    res.send( data )
})

//根据用户的id获取当前登录的用户信息,只是返回一条数据
router.get('/user', async (req, res, next) => {

    let { mid = '' } = req.query


    let data = {}//最终要返回的数据格式  msg,status,result
    //1. 写sql
    let sql = ` SELECT *,CONCAT('${API_URL}/uploads/avatar/',head_photo_url) AS head_photo_url FROM e_member WHERE mid='${mid}'`
    //2. 执行sql
    let { result } = await MyQuery(sql) //{ err,result }

    if (result.length == 0) {
        data = {
            "msg": "查无此人",
            "status": 500
        }
        res.send(data)
        return
    }

    delete result[0].password
    // res.send(result[0])
    // return

    //3. 要处理成规范、格式化的json数据
    data = {
        msg: 'OK',
        status: 200,
        result: result[0] //只是返回一条数据
    }
    res.send(data)
})


//UPDATE e_member SET realname= '张三' ,sex=2,birthdate=1641863125983,city='北京' WHERE mid='cd2e64d4-4382-42f9-bd27-b5f05a8571af'

//根据用户的mid修改用户的信息，除头像和密码之外
router.put('/user', async (req, res, next) => {

    let { realname = '', sex = '', city = '', birthdate = '', mid = '' } = req.body

    let data = {}//最终要返回的数据格式  msg,status,result

    //都需要传递参数
    if (realname == '' || sex == '' || city == '' || birthdate == '' || mid == '') {
        data = {
            "msg": "请传递必要参数",
            "status": 500
        }
        res.send(data)
        return
    }

    //1. 写sql
    let sql = ` UPDATE e_member SET realname= '${realname}' ,sex=${sex},birthdate=${birthdate},city='${city}' WHERE mid='${mid}'
    `
    //2. 执行sql
    let { result } = await MyQuery(sql) //{ err,result }

    //3. 要处理成规范、格式化的json数据 //affectedRows > 0
    data = {
        msg: 'OK',
        status: 200,
    }
    res.send(data)
})


//获取当前登录用户的报名信息 
//
router.get('/orders', async (req, res, next) => {

    let { mid = '' } = req.query

    let data = {}//最终要返回的数据格式  msg,status,result

    if (mid == '') {
        data = {
            msg: '请传递必要参数',
            status: 500
        }
        res.send(data)
        return
    }

    //1. 写sql
    let sql = `SELECT *,CONCAT('${API_URL}/uploads/courses/',image_src) AS image_src FROM e_order AS o JOIN e_course AS c ON o.cid = c.cid WHERE mid = '${mid}' `
    //2. 执行sql
    let { result } = await MyQuery(sql) //{ err,result }

    //3. 要处理成规范、格式化的json数据
    data = {
        msg: 'OK',
        status: 200,
        result
    }
    res.send(data)
})

// 更新头像
router.post('/uploadhead', async (req, res, next) => {

    const form = formidable({  //实例了一个接收表单的实例对象（可以有文件数据也有可以普通的字符串数据）
        uploadDir: 'temp',//temporary  上传文件临时存放的地址
    });

    form.parse(req, async (err, fields, files) => {

        let oldpath = files.f.filepath
        let mid = fields.mid //用户的id
        //2. 随机名
        let extname = path.extname(files.f.originalFilename) //获取扩展名
        let head_photo_url = uuidv4() + extname //图片的新名称
        let newPath = path.join('uploads/avatar', head_photo_url) //拼接后的新路径
        fs.renameSync(oldpath, newPath)

        let data = {}//最终要返回的数据格式  msg,status,result
        //1. 写sql
        let sql = ` UPDATE e_member SET head_photo_url = '${head_photo_url}' WHERE mid='${mid}' `
        //2. 执行sql
        let { result } = await MyQuery(sql) //{ err,result }

        //3. 要处理成规范、格式化的json数据 //用affetcdRows做一下判断
        data = {
            msg: 'OK',
            status: 200,
            result: `${API_URL}/uploads/avatar/${head_photo_url}`
        }
        res.send(data)

    });

})

module.exports = router;
